package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequirePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    // 处理查询所有员工请求
    @RequestMapping("/list")
    @RequirePermission(name="员工页面",expression="employee:list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {//把qo传到list.jsp的方法一,手动贴注解

        model.addAttribute("pageResult", employeeService.query(qo));
        // 查询所有部门往模型存入，提供数据，让员工列表页面显示出来以供用户选择
        model.addAttribute("departments",departmentService.listAll());
        //把qo传到list.jsp的方法二:
        //model.addAttribute("qo",qo);

        return "employee/list"; // 找视图 /WEB-INF/views/employee/list.jsp
    }

    // 新增或修改
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee,Long[] ids) {
        if (employee.getId() == null) {
            // 新增
            employeeService.save(employee,ids);
        } else {
            employeeService.update(employee,ids); // 修改
        }
        return "redirect:/employee/list.do"; // 让浏览器重新发一次请求
    }

    // 处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            if (id != null) {
                employeeService.delete(id);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(false,"系统异常,请联系管理员");// 让浏览器重新发一次请求
    }

    // 去新增或去修改页面
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        //查询所有角色
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles",roles);
        List<Department> departments = departmentService.listAll();
        // 查询所有部门往模型存入，提供数据，让员工新增修改时显示出来以供用户选择
        model.addAttribute("departments", departments);
        if (id != null) { // 表示去修改
            Employee employee = employeeService.get(id);
            model.addAttribute("employee", employee);
        }
        return "employee/input"; // 让浏览器重新发一次请求
    }
}
